// import router from '../router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import store from '../store'
import { UserModel } from '@/models'
import { toLoginCenter, isRedirect, handleRedirect } from './auth'
// import ClientMonitor from 'skywalking-client-js'

NProgress.configure({
    showSpinner: false
})

const whiteList = ['/login']
const userModel = new UserModel()

const before = (to, from, next) => {
    NProgress.start()
    if (isRedirect()) {
        handleRedirect()
        NProgress.done()
        return
    }

    // let fromPath = from.path
    const nextPath = to.path
    const token = store.getters.token

    if (token !== undefined) {
        // 已经登录过的情况下
        // next({ path: '/' }) 会再次回到这个位置检查用户信息
        if (store.getters.avatar.name === undefined) {
            userModel
                .loadInfo()
                .then(info => {
                    if (info.dataRole && info.dataRole.length > 0) {
                        store.dispatch('user/processInfo', info).then(_ => {
                            NProgress.done()
                            next({
                                ...to,
                                replace: true
                            })
                        })
                    } else {
                        Message.warning('当前用户没有分配数据权限，无法正常访问，请联系管理员进行权限配置后访问')
                    }
                })
                .catch(err => {
                    console.error('query info error in router hooks', err)
                    store.dispatch('user/resetToken').then(() => {
                        NProgress.done()
                        // request 中处理跳转登录
                    })
                })
        } else {
            NProgress.done()
            next()
        }
    } else {
        NProgress.done()
        if (whiteList.includes(nextPath)) {
            next()
        } else {
            toLoginCenter()
        }
    }
}

const after = () => {
    // if (process.env.NODE_ENV !== 'development') {
    //     ClientMonitor.setPerformance({
    //         collector: window.api_source.skywalkingCollector,
    //         service: window.api_source.skywalkingService,
    //         serviceVersion: window.api_source.skywalkingserviceVersion,
    //         pagePath: location.href
    //     })
    // }
    NProgress.done()
}

const errorHandler = err => {
    console.log('router error', err)
}

const configHooks = router => {
    router.beforeEach(before)
    router.afterEach(after)
    router.onError = errorHandler
}

export default configHooks
